package com.example.newznbk;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

import adapter.ListMenuTwoAdapter;
import adapter.ListMunuAdapter;
import adapter.MainPagerAdapter;
import adapter.RecentStudyAdapter;
import base.AndroidBug5497Workaround;
import base.BaseActivity;
import utils.ActivityUtil;
import utils.ToastUtils;
import view.DisciplinePopWindow;

/*
* 侧滑菜单
* */
public class MainActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private SlidingMenu mMenu=null;
    private int top;
    private FragmentTransaction transAction;
    private View view;
    private View v_masker;
    private TextView mTvLoginOut;

    private TextView mTvDicName;
    private ImageView mArrowIv;

    ViewPager mViewPager;
    MainPagerAdapter mainPagerAdapter;
    static int[] PAGE_RESOURCE = {R.mipmap.p0, R.mipmap.p1,R.mipmap.p2};
    SwipeRefreshLayout mSwipeRefreshLayout;

    RecyclerView mRecyclerView;
    RecentStudyAdapter mRecyclerAdapter;

    AppBarLayout mAppBarLayout;
    CollapsingToolbarLayout collapsingToolbarLayout;


//    private ViewPager vp_guide;
//    private List<ImageView> mImgList;//导航图集合
//    private LinearLayout ll_container;//小圆点容器
//    private int mCurrentIndex = 0;//当前小圆点的位置
//    private int[] imgArray = {R.mipmap.p0, R.mipmap.p1, R.mipmap.p2};


    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    MainActivity activity = (MainActivity) msg.obj;
                    activity.mSwipeRefreshLayout.setRefreshing(false);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //这里使用的是slidingmenu的第三种用法。
        setContentView(R.layout.slidingmenu_main);
        view=getLayoutInflater().inflate(R.layout.main_menu_login, null, false);
        // 管理activity
        ActivityUtil.getInstance().addActivity(this);
//        initMainView();
        //初始化菜单
        initMenu(view);
        top=getTitleTop();

        initToolbar();
        initView();
        initRecyle();
        initViewAction();

        AndroidBug5497Workaround.assistActivity(findViewById(android.R.id.content));
    }

    /**
     * 初始化工具栏
     */
    public void initToolbar() {
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        //设置Titlebar title 展开时title 位置
        collapsingToolbarLayout.setExpandedTitleGravity(Gravity.NO_GRAVITY);
        //设置Titlebar title 折叠后title 位置
        collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        //设置Titlebar title 折叠后字体颜色
        collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
        //设置Titlebar title 展开后字体颜色
        collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#00000000"));
        //设置折叠后titlebar颜色
        collapsingToolbarLayout.setContentScrimColor(Color.parseColor("#99FF0000"));
        //设置title 是否可以被展开
        collapsingToolbarLayout.setTitleEnabled(true);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //设置显示返回按钮 返回按钮的监听需在onOptionsItemSelected(MenuItem item) 方法中进行监听 返回按钮ID：android.R.id.home
        actionBar.setDisplayHomeAsUpEnabled(true);
        //设置是否显示titlebar title 默认为true 默认显示项目名称
        actionBar.setDisplayShowTitleEnabled(true);
        //自定义显示title内容
        actionBar.setTitle("松松");

        actionBar.setDisplayHomeAsUpEnabled(false);
    }

    /*
    * 初始化最近学习列表项
    * */
    private void initRecyle() {
        String[] itemArr = new String[5];
        for (int i = 0; i < 5; i++) {
            itemArr[i] = "第" + i + "行数据";
        }
        mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        RecentStudyAdapter adpter = new RecentStudyAdapter(MainActivity.this, itemArr);
        mRecyclerView.setAdapter(adpter);
        adpter.setOnItemClickListener(new RecentStudyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.i("点击", position + "");

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        // 判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            ((RelativeLayout) findViewById(R.id.sou_s)).setPadding(0, top+10, 0, 0);
        }
    }

    private int getTitleTop() {
        Class<?> c=null;
        Object obj=null;
        Field field=null;
        int x=0, sbar=0;
        try {
            c=Class.forName("com.android.internal.R$dimen");
            obj=c.newInstance();
            field=c.getField("status_bar_height");
            x=Integer.parseInt(field.get(obj).toString());
            sbar=getResources().getDimensionPixelSize(x);// 状态栏高度
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        Log.e("状态栏高度:", sbar + ":" + x);
        return sbar;
    }

    private void initMenu(View view) {
        mMenu=(SlidingMenu) findViewById(R.id.slidingmenulayout);
        mMenu.setMode(SlidingMenu.LEFT);
        // 设置触摸屏幕的模式
        mMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        //获取屏幕宽高
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 设置滑动菜单视图的宽度
        mMenu.setBehindWidth(dm.widthPixels * 4 / 5);
        // 设置渐入渐出效果的值
        mMenu.setFadeDegree(0.35f);
        mMenu.setMenu(view);
        initaaaView(view);//初始化侧边视图

        initViewTwo(view);

        mMenu.setOnOpenListener(new SlidingMenu.OnOpenListener() {
            @Override
            public void onOpen() {
                v_masker.setVisibility(View.VISIBLE);
            }
        });

        mMenu.setOnClosedListener(new SlidingMenu.OnClosedListener() {
            @Override
            public void onClosed() {
                v_masker.setVisibility(View.GONE);
            }
        });




    }

    private void initView() {

        ImageView mImageView=(ImageView) findViewById(R.id.iv_personal_icon);
        mImageView.setOnClickListener(this);

        v_masker = (View) findViewById(R.id.view_masker);

        mTvLoginOut = (TextView) findViewById(R.id.tv_login_out);
//        mTvLoginOut.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        mTvDicName = (TextView) findViewById(R.id.tv_discipline_name);
        mArrowIv = (ImageView) findViewById(R.id.iv_arrow);

        //下拉是刷新组件设置
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
        mSwipeRefreshLayout.setOnRefreshListener(MainActivity.this);
        //设置样式刷新显示的位置
        mSwipeRefreshLayout.setProgressViewOffset(true, -20, 100);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2, R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        //RecyclerView 设置
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); //设置RecyclerView布局方式线性布局
        mRecyclerView.setAdapter(mRecyclerAdapter);

        //ViewPager Define
        mViewPager = (ViewPager) findViewById(R.id.toolbar_viewpager);
        mainPagerAdapter = new MainPagerAdapter(MainActivity.this, PAGE_RESOURCE);
        mViewPager.setAdapter(mainPagerAdapter);
        mViewPager.setCurrentItem(10 * PAGE_RESOURCE.length, true);

//        vp_guide = (ViewPager) findViewById(R.id.vp_guide);
//        ll_container = (LinearLayout) findViewById(R.id.ll_container);
//        mImgList = new ArrayList<>();
//        for (int i = 0; i < imgArray.length; i++) {
//            ImageView imageView = new ImageView(this);//设置viewpage页面显示
//            imageView.setImageResource(imgArray[i]);
//            mImgList.add(imageView);
//            ImageView dot = new ImageView(this);
//            if (i == mCurrentIndex) {
//                dot.setImageResource(R.mipmap.ic_launcher_round);//设置当前页的圆点
//            } else {
//                dot.setImageResource(R.mipmap.ic_launcher);//其余页的圆点
//            }
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
//                    .LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//            if (i > 0) {
//                params.leftMargin = 10;//设置圆点边距
//            }
//            dot.setLayoutParams(params);
//            ll_container.addView(dot);//将圆点添加到容器中
//        }
//        vp_guide.setAdapter(new MyAdapter(mImgList));
//        //添加监听
//        vp_guide.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int
//                    positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                //根据监听的页面改变当前页对应的小圆点
//                mCurrentIndex = position;
//                for (int i = 0; i < ll_container.getChildCount(); i++) {
//                    ImageView imageView = (ImageView) ll_container.getChildAt(i);
//                    if (i == position) {
//                        imageView.setImageResource(R.mipmap.ic_launcher_round);
//                    } else {
//                        imageView.setImageResource(R.mipmap.ic_launcher);
//                    }
//                }
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });



        mAppBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
//        mAppBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
//            @Override
//            public void onStateChanged(AppBarLayout appBarLayout, AppBarStateChangeListener.State state) {
//                Log.d("STATE", state.name());
//                if (state == State.EXPANDED) {
//                    Log.e("==下拉==","======展开状态======");
//                    //展开状态
//                    Toast.makeText(MainActivity.this, "展开", Toast.LENGTH_SHORT).show();
////                    mTvTittle.setText("展开1111");
//
//                } else if (state == State.COLLAPSED) {
//                    Log.e("==下拉==","======折叠状态======");
//                    //折叠状态
//                    Toast.makeText(MainActivity.this, "折叠状态", Toast.LENGTH_SHORT).show();
////                    mTvTittle.setText("折叠状态2322222");
//                } else {
//
//                    //中间状态
////                    Toast.makeText(getActivity(),"中间状态",Toast.LENGTH_SHORT).show();
//
//                }
//            }
//        });

//        menuListView = (ListView) findViewById(R.id.list_menu);
//        DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) menuListView.getLayoutParams();
//        params.width = (int)(CombinaActivity.this.getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.7);
//        params.topMargin = getStatusBarHeight();
//        menuListView.setLayoutParams(params);
//        View headerView = LayoutInflater.from(this).inflate(R.layout.item_list_menu_title, null);


    }

    private void initaaaView(View view) {
        ListView listView=(ListView) view.findViewById(R.id.listview_menu);
        listView.setAdapter(new ListMunuAdapter(MainActivity.this));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 1:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 2:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 3:
//                        Intent intent=new Intent(ZYiMainActivity.this, ShakeActivity.class);
//                        startActivity(intent);
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 4:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 5:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                }
            }
        });
    }

    private void initViewTwo(View view) {
        ListView listView=(ListView) view.findViewById(R.id.listview_menu_two);
        listView.setAdapter(new ListMenuTwoAdapter(MainActivity.this));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                    case 1:
                        ToastUtils.show(MainActivity.this, "点击了 id=" + i);
                        break;
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_personal_icon:
                mMenu.showMenu();
                break;
        }
    }

    private DisciplinePopWindow mDisciplinePopWindow;
    public void click(View view) {
//        View customView = View.inflate(this, R.layout.layout_te111st, null);
//        new PopWindow.Builder(this)
//                .setStyle(PopWindow.PopWindowStyle.PopDown)
//                .setView(customView)
//                .setControlViewAnim(mArrowIv, R.anim.btn_rotate_anim_1, R.anim.btn_rotate_anim_2, true)
//                .show(view);

        mDisciplinePopWindow = new DisciplinePopWindow(MainActivity.this,mTvDicName,mArrowIv,view);
        mDisciplinePopWindow.setClippingEnabled(false);//使popupwindow显示为全屏
        mDisciplinePopWindow.showAtLocation(mArrowIv, Gravity.TOP, 0, 0);
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void initViewAction() {
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0) {
                    mSwipeRefreshLayout.setEnabled(true);
                } else {
                    mSwipeRefreshLayout.setEnabled(false);
                }
            }
        });

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //解决滑动冲突
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        mSwipeRefreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mSwipeRefreshLayout.setEnabled(true);
                        break;
                }
                //方案二
//                v.performClick(); //触发OnClick方法
//                mViewPager.getParent().requestDisallowInterceptTouchEvent(true); //防止父容器阻断子控件事件
                return false;
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), MainActivity.PAGE_RESOURCE[position % MainActivity.PAGE_RESOURCE.length]);
                Palette palette = Palette.from(bitmap).generate();
                Palette.Swatch swatch = palette.getVibrantSwatch();
                if (swatch == null) {
                    swatch = palette.getMutedSwatch();
                }
                int color = swatch.getRgb();
                collapsingToolbarLayout.setContentScrimColor(color);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onRefresh() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg = MainActivity.handler.obtainMessage();
                msg.obj = MainActivity.this;
                msg.what = 0;
                MainActivity.handler.sendMessage(msg);
            }
        }, 2000);
    }


    /*
    * 初始化学习模块
    * */
    private LinearLayout mLayoutSystemReview;
    private void initLearningModule(){

        /*
        * xitong
        * */
        mLayoutSystemReview = (LinearLayout) findViewById(R.id.layout_system_review);
        mLayoutSystemReview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent=new Intent(MainActivity.this, ShakeActivity.class);
//                        startActivity(intent);
            }
        });

    }


}
